﻿using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

public class SkillTimePoint
{
    public float exceTime; //开始执行的时间
    public MethodInfo exceFuc;//需要执行的方法

    public SkillTimePoint(float exceTime, MethodInfo methodInfo)
    {
        this.exceTime = exceTime;
        this.exceFuc = methodInfo;
    }
}

public class SkillTimeNode
{
    public float runTime; //技能持续的时间,这里进行存储做倒计时用
    public bool exExced; //是否已经执行完
    public object udata; //用户数据

    public SkillTimePoint TimePoint;

    public SkillTimeNode(SkillTimePoint pt)
    {
        this.TimePoint = pt;
        this.runTime = pt.exceTime;
        this.exExced = false;
        this.udata = null;
    }
}

public struct SkillTimeLine
{
    private List<SkillTimeNode> timeLineNodeList;
    public CharactorCtrl owner; 
    public int skillId;

    public bool isRuning ; //技能是否正在被执行
    public Action OnComplate; //技能结束的回调
    public void Init()
    {
        timeLineNodeList = null;
        isRuning = false;
        owner = null;
        skillId = 0;
    }

    public bool StartSkill(CharactorCtrl owner, int skillId, Action OnComplate)
    {
        if (this.isRuning)
        {
            return false;
        }

        List<SkillTimeNode> timeLine = SkillManager.Instance.GetSkillTimeLineNode(skillId);
        if (timeLine == null)
        {
            return false;
        }

        this.timeLineNodeList = timeLine;
        this.isRuning = true;
        
        this.owner = owner;
        this.skillId = skillId;
        this.OnComplate = OnComplate;
        return true;
    }

    public void OnUpdate(float dt)
    {
        if (!isRuning)
        {
            return;
        }

        if (timeLineNodeList == null)
        {
            return;
        }

        bool endFlag = true;
        for (int i = 0; i < timeLineNodeList.Count; i++)
        {
            SkillTimeNode node = timeLineNodeList[i];
            if (node.exExced)
            {
                continue;
            }
            node.runTime -= dt;
            if (node.runTime <= 0)
            {
                node.exExced = true;
                object[] paramsData = new object[] { owner, skillId, node.udata };
                node.TimePoint.exceFuc.Invoke(null, paramsData);
                Debug.Log("执行方法：" + node.TimePoint.exceFuc.Name);
            }

            endFlag = false;
        }

        if (endFlag)
        {
            isRuning = false;
            timeLineNodeList = null;
            OnComplate?.Invoke();
        }
    }
}

